/*
 * softtimer.h
 *
 *  Created on: 2023年12月29日
 *      Author: Cheney.Tan
 */

#ifndef SOFTTIMER_H_
#define SOFTTIMER_H_
#include "stdint.h"

//使能 从定时器开始计时后进过的时间
#define SOFTTIMER_STASTISTIC_TIME_PASSED_FROM_START_EN 1
typedef enum
{
	E_SOFTTIMER_SUSPEND = 0,
	E_SOFTTIMER_RUNNING,
	E_SOFTTIMER_STOP
}e_softtimer_state;

class softtimer {
private:
	static softtimer *head, *end;
	static uint32_t tick_last, time_now_ms;

	softtimer *prev, *next;
	uint32_t timeout_ms;
	uint32_t time_passed;
#if SOFTTIMER_STASTISTIC_TIME_PASSED_FROM_START_EN == 1
	uint64_t time_passed_from_start;
#endif
	void (*callback)(softtimer *timer, void *param);
	void *param;
	struct
	{
		uint32_t enable :1;
		uint32_t repeat_mode :1;
		uint32_t repeat_count_in_need :15;
		uint32_t repeat_count :15;	//specific the times to repeat
	}ctrl_bits;

	e_softtimer_state state;

public:
	const char *alias;

	softtimer();
	softtimer(const char *alias);
	softtimer(uint32_t timeout, void (*cb)(softtimer *timer, void *param), void *param);
	virtual ~softtimer();

	void start(void);
	void pause(void);
	void stop(void);
	void reset(void);
	void set_timeout(uint32_t timeout);
	void set_callback(void (*cb)(softtimer *timer, void *param), void *param);
	//设置有限次重复
	void set_repeat(bool enable, uint16_t count);
	//设置无限重复使能/失能
	void set_repeat(bool enable);

	//获取定时器状态
	e_softtimer_state get_state(void);
	//获取当前的tick值（ms)
	static uint32_t get_tick_ms(void);
#if SOFTTIMER_STASTISTIC_TIME_PASSED_FROM_START_EN == 1
	//从定时器开始计时后过去的时间
	uint64_t get_time_passed_ms(void);
#endif
	//定时器事务处理，参数为传入过了多少毫秒，较适合OS环境
	static void process_handle(uint16_t time_passed_ms);
	//定时器事务处理，参数为当前tick值 & 每过1ms tick值的增量，较适合裸机环境
	static void process_handle(uint32_t tick_now, uint16_t ms_cnt_per_tick);
};

#endif /* SOFTTIMER_H_ */
